"""
API路由模块
"""

from fastapi import APIRouter, HTTPException, Depends
from typing import List, Dict, Any, Optional
from fastapi.responses import StreamingResponse
import json

from ..schemas.base import ChatRequest, AgentResponse, TaskStatus, ToolResumeRequest
from ..graphs.workflow import execute_workflow, resume_workflow
from ..core.logging import logger

# 创建API路由器
router = APIRouter()

async def sse_event_generator(generator):
    """一个通用的异步生成器，用于将任何生成器的输出格式化为SSE事件"""
    try:
        async for chunk in generator:
            yield f"data: {chunk}\n\n"
    except Exception as e:
        logger.error(f"在SSE事件流中发生错误: {str(e)}", exc_info=True)
        error_message = json.dumps({
            "type": "error",
            "content": f"处理流时发生错误: {str(e)}"
        })
        yield f"data: {error_message}\n\n"

@router.post("/chat")
async def chat(request: ChatRequest):
    """
    处理聊天请求，通过Server-Sent Events (SSE)进行流式响应。
    这将启动或继续一个对话，直到需要人工干预或对话结束。
    """
    try:
        logger.info(f"收到SSE聊天请求: session_id={request.session_id}, messages={len(request.messages)}")
        
        # 获取工作流的响应生成器
        response_generator = execute_workflow(
            initial_messages=request.messages,
            session_id=request.session_id
        )
        
        # 将其包装在SSE格式化生成器中
        return StreamingResponse(sse_event_generator(response_generator), media_type="text/event-stream")
    
    except Exception as e:
        logger.error(f"启动SSE流时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/chat/resume")
async def chat_resume(request: ToolResumeRequest):
    """
    在人工批准工具调用后，恢复工作流的执行。
    """
    try:
        logger.info(f"收到工作流恢复请求: session_id={request.session_id}")
        
        response_generator = resume_workflow(
            tool_outputs=request.tool_outputs,
            session_id=request.session_id
        )
        
        return StreamingResponse(sse_event_generator(response_generator), media_type="text/event-stream")
        
    except Exception as e:
        logger.error(f"恢复工作流时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/execute", response_model=TaskStatus)
async def execute_tool(tool_call: Dict[str, Any]) -> TaskStatus:
    """
    执行工具调用
    
    Args:
        tool_call: 工具调用请求
        
    Returns:
        TaskStatus: 任务状态
    """
    try:
        logger.info(f"收到工具执行请求: {tool_call.get('name')}")
        
        # 这里可以添加工具执行逻辑
        # 目前直接返回未实现
        
        return TaskStatus(
            task_id="task_not_implemented",
            status="failed",
            error="此API端点尚未实现"
        )
    
    except Exception as e:
        logger.error(f"执行工具时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/tools", response_model=List[Dict[str, Any]])
async def list_tools() -> List[Dict[str, Any]]:
    """
    列出可用工具
    
    Returns:
        List[Dict[str, Any]]: 工具列表
    """
    try:
        from ..tools.tool_executor import tool_executor
        
        # 获取工具列表
        tools = tool_executor.list_tools()
        
        return tools
    
    except Exception as e:
        logger.error(f"列出工具时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/health")
async def health_check() -> Dict[str, str]:
    """
    健康检查
    
    Returns:
        Dict[str, str]: 健康状态
    """
    return {"status": "ok"} 